<?php


namespace app\admin\controller;

use app\admin\model\AdminNode;
use app\admin\model\AdminRole;
use think\Controller;
use think\Db;
use think\Request;


class Role extends Controller {

    protected $middleware = [
        "CheckPermission",
        "Log"
    ];

    private $roleModel;
    private $nodeModle;
    private $adminInfo = null;
    public function initialize()
    {
        parent::initialize();
        $this->nodeModle = new AdminNode();
        $this->roleModel = new AdminRole();
        $this->adminInfo = session('user');

    }

    // 角色列表
    public function index(Request $request){

        $params = $request->get();
        $role_name = isset($params['role_name']) ? trim($params['role_name']) : '';
        $where[] = ['is_del','=',0];

        if($role_name!='') $where[] = ['role_name','like','%' . trim($role_name) . '%'];

        $list = $this->roleModel->getRoleList($where,15,$params);

        return $this->view->fetch('index',['list'=>$list,'total'=>$list->total()]);
    }


    public function add(Request $request){

        if($request->isPost()){

            $post = $request->post();
            $role_name = isset($post['role_name']) ? trim($post['role_name']) : '';
            $remark = isset($post['remark']) ? trim($post['remark']) : '';

            if($role_name=='') {
                $this->error('角色名称是必填项不能为空');
            }

            $id = $this->roleModel->insertOne(['role_name'=>$role_name,'remark'=>$remark]);

            if ($id) {

                // 写入必须的权限菜单 【1 主面板 2欢迎页 26 个人资料】
                $needNodeId = [1,2,26];
                $insert = [];
                foreach ($needNodeId as $k=>$v){
                    $insert[$k]['node_id'] = $v;
                    $insert[$k]['role_id'] = $id;
                    $insert[$k]['create_time'] = time();
                }
                Db::table('admin_role_node')->insertAll($insert);

                $this->success('添加角色成功',url('admin/role/index'));
            } else {

                $this->error('添加角色失败');
            }

        } else {

            return $this->view->fetch('add');
        }
    }


    // 删除角色
    public function del(Request $request){
        $params = $request->get();

        $role_id = isset($params['role_id']) ? intval($params['role_id']) : 0;
        if ($role_id>0) {

            $rt = $this->roleModel->delOne($role_id);
            if ($rt) {

                $res['err'] = 0;
                $res['msg'] = '删除成功';
                return response($res,200,[],'json');

            } else {
                $res['err'] = 1002;
                $res['msg'] = '删除失败';
                return response($res,200,[],'json');
            }

        } else {

            $res['err'] = 1001;
            $res['msg'] = '参数错误role_id不能为空';
            return response($res,200,[],'json');
        }

    }


    // 角色编辑
    public function edit(Request $request){

        if($request->isPost()){

            $post = $request->post();
            $role_name = isset($post['role_name']) ? trim($post['role_name']) : '';
            $remark = isset($post['remark']) ? trim($post['remark']) : '';
            $role_id = isset($post['role_id']) ? intval($post['role_id']) : 0;


            if($role_name=='') $this->error('角色名称是必填项不能为空');
            if($role_id==0) $this->error('参数错误role_id不能为空');

            $rt = $this->roleModel->updateOne($role_id,['role_name'=>$role_name,'remark'=>$remark]);

            if ($rt) {

                $this->success('编辑角色成功',url('admin/role/index'));
            } else {

                $this->error('编辑角色失败');
            }

        } else {
            $role_id = $request->get('role_id',0);
            if($role_id==0) $this->error('参数错误role_id不能为空');

            $arr = $this->roleModel->getOne($role_id);

            return $this->view->fetch('edit',['info'=>$arr]);
        }
    }

    //设置权限使用ztree
    public function setRolePermission(Request $request) {

        if($request->isPost()){
            $role_id = $request->post('role_id',0);
            if($role_id==0){
                $res['err'] = 1001;
                $res['msg'] = '参数错误role_id不能为空';
                return response($res,200,[],'json');
            }

            $ids = $request->post('ids','');
            if($ids==''){
                $res['err'] = 1002;
                $res['msg'] = '至少选则一个节点';
                return response($res,200,[],'json');
            }

            $idArr = explode(',',trim($ids,','));

            // 删除已有的权限
            $hasMap[] = ['is_del','=',0];
            $hasMap[] = ['role_id','=',$role_id];
            $count = Db::table('admin_role_node')->where($hasMap)->count();
            if($count>0){
                Db::table('admin_role_node')->where($hasMap)->update(['is_del'=>1]);
            }

            // 写入新的权限
            $newData = [];
            foreach ($idArr as $k=>$v){
                $newData[$k]['role_id'] = $role_id;
                $newData[$k]['node_id'] = $v;
                $newData[$k]['create_time'] = time();
            }
            $num = Db::table('admin_role_node')->insertAll($newData);

            if($num){
                $res['err'] = 0;
                $res['msg'] = '权限设置成功';
                return response($res,200,[],'json');
            } else {
                $res['err'] = 1003;
                $res['msg'] = '设置权限失败';
                return response($res,200,[],'json');
            }

        } else {

            $role_id = $request->get('role_id',0);
            if($role_id==0) $this->error('参数错误role_id不能为空');

            $nodes = $this->nodeModle->getAll();
            // 默认勾选的
            $defaultNeed = [1,2];

            //已有权限默认勾选上
            $myMap[] = ['is_del','=',0];
            $myMap[] = ['role_id','=',$role_id];
            $myAll = Db::table('admin_role_node')->where($myMap)->column('node_id');

            foreach ($nodes as &$rows){
                $con = Db::table('admin_node')->where('parent_id','=',$rows['id'])->count();
                if($con > 0){
                    $rows['open'] = true;
                }
                if (in_array($rows['id'],$defaultNeed)){
                    $rows['checked'] = true;
                }
                if(in_array($rows['id'],$myAll)){
                    $rows['checked'] = true;
                }

            }


            return $this->view->fetch('set_role_permission',['nodes'=>json_encode($nodes),'role_id'=>$role_id]);
        }


    }


}